import {
  storeToken,
  fetchStoredToken,
  removeStoredToken,
} from "../../utils/token";
import { get } from "../../utils/request";
const appInstance = getApp();
Page({
  data: {
    avatarUrl: appInstance.globalData.defaultAvatarUrl,
    nickname: "",
    avatar: "",
    isLogin: false,
  },
  onLoad() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    if (fetchStoredToken()) {
      const { nickname, avatar } = wx.getStorageSync("user") || {};
      this.setData({
        nickname,
        avatar,
        isLogin: true,
      });
    }
  },
  onShareAppMessage() {
    return {
      title: "分享小程序",
      path: "/pages/index/index",
      success: function (res) {
        console.log("分享成功", res);
      },
      fail: function (res) {
        console.log("分享失败", res);
      },
    };
  },
  onShareTimeline() {
    return {
      title: "分享朋友圈",
      success: function (res) {
        console.log("分享成功", res);
      },
      fail: function (res) {
        console.log("分享失败", res);
      },
    };
  },
  logout() {
    removeStoredToken();
    wx.reLaunch({
      url: "/pages/profile/profile",
    });
  },
  async loginUser() {
    try {
      const { code } = await new Promise((resolve, reject) => {
        wx.login({
          success: resolve,
          fail: reject,
        });
      });
      if (code) {
        const {
          data: { token, nickname, avatar },
        } = await get("/login", {
          data: { code },
        });
        storeToken(token);
        if (nickname) {
          this.setData({
            avatar,
            nickname,
            isLogin: true,
          });
          wx.setStorageSync("user", { nickname, avatar });
          wx.showToast({ title: `登录成功`, duration: 1000 });
        } else {
          const confirm = await wx.showModal({
            title: "登录成功，您还未完善信息",
            content: "去完善信息吧",
            confirmText: "去完善",
          });
          if (confirm) {
            return wx.navigateTo({ url: "/pages/improve/improve" });
          }
        }
      }
    } catch (error) {
      wx.showToast({
        title: error.message || "Login failed.",
        icon: "error",
        duration: 2000,
      });
    }
  },
});
